package be.jhd.appserver.weblogic;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import be.jhd.appserver.Command;
import be.jhd.appserver.CommandSender;
import be.jhd.appserver.weblogic.command.WeblogicConfig;

public abstract class AbstractCommandSender<T extends Command> implements CommandSender<T> {
	
	protected WeblogicConfig getConfig() {
		return config;
	}

	private final static Logger LOG = LoggerFactory.getLogger(AbstractCommandSender.class);
	
	private final WeblogicConfig config;
	
	public AbstractCommandSender(WeblogicConfig config){
		this.config = config;
	}
	
	public final String send(T command){
		final PrintStream actual = System.out;
		try{
			final ByteArrayOutputStream baos = new ByteArrayOutputStream();
			final PrintStream out = new PrintStream(baos);
			System.setOut(out);
			
			executeCommand(command);
			
			final String result =  new String(baos.toByteArray());
			LOG.debug(result);
			return result;
		}catch(Exception exc){
			LOG.error("Error while sending a Command", exc);
			throw new CommandSenderException("Error while sending a Command", exc);
		}finally{
			System.setOut(actual);
		}

	}
	
	protected abstract void executeCommand(T command) throws Exception;
}
